package com.yjt.fresh.fragment.order;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.wzgiceman.rxretrofitlibrary.retrofit_rx.Api.BaseResultEntity;
import com.wzgiceman.rxretrofitlibrary.retrofit_rx.http.HttpManager;
import com.wzgiceman.rxretrofitlibrary.retrofit_rx.listener.HttpOnNextListener;
import com.yjt.fresh.R;
import com.yjt.fresh.activity.AtyAfterSale;
import com.yjt.fresh.activity.AtyCheckExpress;
import com.yjt.fresh.activity.AtyComment;
import com.yjt.fresh.activity.AtyCommentCenter;
import com.yjt.fresh.activity.AtyContactUs;
import com.yjt.fresh.activity.AtyOrderDetail;
import com.yjt.fresh.activity.AtyPay;
import com.yjt.fresh.adpater.AdpRvMyOrder;
import com.yjt.fresh.api.ApiCancelOrder;
import com.yjt.fresh.api.ApiConfirmReceive;
import com.yjt.fresh.api.ApiDeleteOrder;
import com.yjt.fresh.api.ApiGetOrderList;
import com.yjt.fresh.api.ApiNoticeSendGoods;
import com.yjt.fresh.base.BaseSimpleFragment;
import com.yjt.fresh.bean.BeanMyPoints;
import com.yjt.fresh.bean.BeanOrder;
import com.yjt.fresh.constant.MyConstants;
import com.yjt.fresh.utils.PreferenceManager;
import com.yjt.fresh.widget.CustomToastResult;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;


/**
 * 订单
 * Created by mcc on 2018-07-27.
 */

public abstract class FrgOrderBase extends BaseSimpleFragment {
    public static final int REQUEST_CODE = 1006;
    private static final int PAGE_SIZE = 20;

    @BindView(R.id.rvAppFrgMyOrder)
    RecyclerView mRv;
    @BindView(R.id.srlAppAtyMyOrder)
    SwipeRefreshLayout mRefreshLayout;
    private AdpRvMyOrder mAdpRvMyOrder;
    private int mNextRequestPage = 1;
    private boolean isLoadMore;
    protected String mStatus;

    @Override
    protected int getContentView() {
        return R.layout.app_frg_my_order;
    }

    @Override
    protected void initView(Bundle savedInstanceState, View view) {
        ButterKnife.bind(this, view);
        setStatus();
    }

    protected abstract void setStatus();

    @Override
    protected void initEvents() {
        initRv();
        getData();
        initClick();
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (getActivity() != null && mStatus != null && isVisibleToUser) {
            mNextRequestPage = 1;
            isLoadMore = false;
            mAdpRvMyOrder.setEnableLoadMore(false);
            setStatus();
            getData();
        }

    }

    private void refresh() {
        mNextRequestPage = 1;
        isLoadMore = false;
        getData();
    }

    private void initClick() {
        mRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                refresh();
            }
        });

        mAdpRvMyOrder.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                isLoadMore = true;
                getData();
            }
        }, mRv);

        mAdpRvMyOrder.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Intent intent = new Intent(mContext, AtyOrderDetail.class);
                intent.putExtra(MyConstants.ORDER_ID, mAdpRvMyOrder.getData().get(position).getORDERS_ID());
                startActivityForResult(intent, REQUEST_CODE);
            }
        });

        mAdpRvMyOrder.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, final int position) {
                switch (view.getId()) {
                    case R.id.tvAppRecycleItemAtyMyOrderContactService:
                        contactService(position);
                        break;
                    case R.id.tvAppRecycleItemAtyMyOrderCancelOrder:
                        final Dialog dialog = new Dialog(mContext, R.style.MyDialog);
                        dialog.setContentView(R.layout.app_dialog_sure_cancel);
                        TextView tvContent = dialog.findViewById(R.id.tvAppDIalogSureCancelContent);
                        TextView tvCancel = dialog.findViewById(R.id.tvAppDialogSureCancelCancel);
                        TextView tvSure = dialog.findViewById(R.id.tvAppDialogSureCancelSure);
                        tvContent.setText("确定要取消订单吗?");
                        tvCancel.setText("取消");
                        tvSure.setText("确定");
                        tvCancel.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                if (dialog != null && dialog.isShowing()) {
                                    dialog.dismiss();
                                }
                            }
                        });
                        tvSure.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                cancelOrder(position);
                                if (dialog != null && dialog.isShowing()) {
                                    dialog.dismiss();
                                }
                            }
                        });
                        dialog.show();
                        break;
                    case R.id.tvAppRecycleItemAtyMyOrderNoticeSend:
                        noticeSend(position);
                        break;
                    case R.id.tvAppRecycleItemAtyMyOrderCheckExpress:
                        checkExpress(position);
                        break;
                    case R.id.tvAppRecycleItemAtyMyOrderConfirmReceive:
                        confirmReceive(position);
                        break;
                    case R.id.tvAppRecycleItemAtyMyOrderService:
                        afterSale(position);
                        break;
                    case R.id.tvAppRecycleItemAtyMyOrderComment:
                        comment(position);
                        break;
                    case R.id.tvAppRecycleItemAtyMyOrderDeleteOrder:
                        deleteOrder(position);
                        break;
                    case R.id.tvAppRecycleItemAtyMyOrderPay:
                        pay(position);
                        break;
                    case R.id.tvAppRecycleItemAtyMyOrderServiceAbove:
                        afterSale(position);
                        break;
                    default:
                        break;
                }
            }
        });
    }

    private void pay(int position) {
        Intent intent = new Intent(mContext, AtyPay.class);
        intent.putExtra(MyConstants.ORDER_MONEY, mAdpRvMyOrder.getData().get(position).getORDERMONEY());
        intent.putExtra(MyConstants.FROM_WHERE, MyConstants.MY_ORDER);
        intent.putExtra(MyConstants.ORDER_ID, mAdpRvMyOrder.getData().get(position).getORDERS_ID());
        intent.putExtra(MyConstants.DEAD_TIME, mAdpRvMyOrder.getData().get(position).getDEADLINE());
        startActivityForResult(intent, REQUEST_CODE);
    }

    HttpOnNextListener<BaseResultEntity> mDeleteOrderListener = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity baseResultEntity) {
            CustomToastResult.show("删除成功");
            refresh();
        }

        @Override
        public void onReLogin() {
            toLogin();
        }
    };

    private void deleteOrder(final int position) {
        final Dialog dialog = new Dialog(mContext, R.style.MyDialog);
        dialog.setContentView(R.layout.app_dialog_sure_cancel);
        TextView tvContent = dialog.findViewById(R.id.tvAppDIalogSureCancelContent);
        TextView tvCancel = dialog.findViewById(R.id.tvAppDialogSureCancelCancel);
        TextView tvSure = dialog.findViewById(R.id.tvAppDialogSureCancelSure);
        tvContent.setText("确定要删除订单吗?");
        tvCancel.setText("取消");
        tvSure.setText("确定");
        tvCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (dialog != null && dialog.isShowing()) {
                    dialog.dismiss();
                }
            }
        });
        tvSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ApiDeleteOrder apiDeleteOrder = new ApiDeleteOrder(mDeleteOrderListener, mContext, true, false, false);
                Map<String, Object> map = new HashMap<>();
                map.put("SESSION_ID", PreferenceManager.getInstance().getUserInfo().getSESSION_ID());
                map.put("ORDERS_ID", mAdpRvMyOrder.getData().get(position).getORDERS_ID());
                apiDeleteOrder.setMap(map);
                HttpManager.getInstance().doHttpDeal(apiDeleteOrder);
                if (dialog != null && dialog.isShowing()) {
                    dialog.dismiss();
                }
            }
        });
        dialog.show();

    }

    private void comment(int position) {
        Intent intent = new Intent(mContext, AtyCommentCenter.class);
        startActivity(intent);
    }

    private void afterSale(int position) {
        Intent intent = new Intent(mContext, AtyAfterSale.class);
        startActivity(intent);
    }

    HttpOnNextListener<BaseResultEntity> mConfirmReceiveListener = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity baseResultEntity) {
            CustomToastResult.show("确认成功");
            refresh();
        }

        @Override
        public void onReLogin() {
            toLogin();
        }
    };

    private void confirmReceive(final int position) {
        final Dialog dialog = new Dialog(mContext, R.style.MyDialog);
        dialog.setContentView(R.layout.app_dialog_sure_cancel);
        TextView tvContent = dialog.findViewById(R.id.tvAppDIalogSureCancelContent);
        TextView tvCancel = dialog.findViewById(R.id.tvAppDialogSureCancelCancel);
        TextView tvSure = dialog.findViewById(R.id.tvAppDialogSureCancelSure);
        tvContent.setText("如确定已收到货，请确认收货，如未收到货，请谨慎确认。");
        tvCancel.setText("取消");
        tvSure.setText("确定");
        tvCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (dialog != null && dialog.isShowing()) {
                    dialog.dismiss();
                }
            }
        });
        tvSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ApiConfirmReceive apiConfirmReceive = new ApiConfirmReceive(mConfirmReceiveListener, mContext, true, false, false);
                Map<String, Object> map = new HashMap<>();
                map.put("SESSION_ID", PreferenceManager.getInstance().getUserInfo().getSESSION_ID());
                map.put("ORDERS_ID", mAdpRvMyOrder.getData().get(position).getORDERS_ID());
                apiConfirmReceive.setMap(map);
                HttpManager.getInstance().doHttpDeal(apiConfirmReceive);
                if (dialog != null && dialog.isShowing()) {
                    dialog.dismiss();
                }
            }
        });

        dialog.show();
    }

    private void checkExpress(int position) {
        Intent intent = new Intent(mContext, AtyCheckExpress.class);
        intent.putExtra(MyConstants.ORDER_ID, mAdpRvMyOrder.getData().get(position).getGOODS().get(0).getORDERS_ID());
        startActivity(intent);
    }

    HttpOnNextListener<BaseResultEntity> mNoticeSendListener = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity baseResultEntity) {
            CustomToastResult.show("提醒成功");
            refresh();
        }

        @Override
        public void onReLogin() {
            toLogin();
        }
    };

    private void noticeSend(int position) {
        ApiNoticeSendGoods apiNoticeSendGoods = new ApiNoticeSendGoods(mNoticeSendListener, mContext, true, false, false);
        Map<String, Object> map = new HashMap<>();
        map.put("SESSION_ID", PreferenceManager.getInstance().getUserInfo().getSESSION_ID());
        map.put("ORDERS_ID", mAdpRvMyOrder.getData().get(position).getORDERS_ID());
        apiNoticeSendGoods.setMap(map);
        HttpManager.getInstance().doHttpDeal(apiNoticeSendGoods);
    }

    HttpOnNextListener<BaseResultEntity> mCancelOrderListener = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity baseResultEntity) {
            CustomToastResult.show("取消成功");
            refresh();
        }

        @Override
        public void onReLogin() {
            toLogin();
        }
    };

    private void cancelOrder(int position) {
        ApiCancelOrder apiCancelOrder = new ApiCancelOrder(mCancelOrderListener, mContext, true, false, false);
        Map<String, Object> map = new HashMap<>();
        map.put("SESSION_ID", PreferenceManager.getInstance().getUserInfo().getSESSION_ID());
        map.put("ORDERS_ID", mAdpRvMyOrder.getData().get(position).getORDERS_ID());
        apiCancelOrder.setMap(map);
        HttpManager.getInstance().doHttpDeal(apiCancelOrder);
    }

    private void contactService(int position) {
        Intent intent = new Intent(mContext, AtyContactUs.class);
        startActivity(intent);
    }

    HttpOnNextListener<List<BeanOrder>> mGetOrderListener = new HttpOnNextListener<List<BeanOrder>>() {
        @Override
        public void onNext(List<BeanOrder> beanOrders) {
            mAdpRvMyOrder.setEmptyView(R.layout.view_empty);
            if (isLoadMore) {
                setData(false, beanOrders);
            } else {
                setData(true, beanOrders);
                mRefreshLayout.setRefreshing(false);
            }
        }

        @Override
        public void onReLogin() {
            toLogin();
        }
    };

    private void setData(boolean isRefresh, List<BeanOrder> data) {
        mNextRequestPage++;
        final int size = data == null ? 0 : data.size();
        if (isRefresh) {
            mAdpRvMyOrder.setNewData(data);
        } else {
            if (size > 0) {
                mAdpRvMyOrder.addData(data);
                mAdpRvMyOrder.loadMoreComplete();
            } else {
                mAdpRvMyOrder.loadMoreEnd(true);
            }
        }
        if (size < PAGE_SIZE) {
            //第一页如果不够一页就不显示没有更多数据布局
            mAdpRvMyOrder.loadMoreEnd(isRefresh);
        } else {
            mAdpRvMyOrder.loadMoreComplete();
        }
    }

    private void getData() {
        ApiGetOrderList apiGetOrderList = new ApiGetOrderList(mGetOrderListener, mContext, true, false, false);
        Map<String, Object> map = new HashMap<>();
        map.put("currentPage", mNextRequestPage);
        map.put("SESSION_ID", PreferenceManager.getInstance().getUserInfo().getSESSION_ID());
        if (!TextUtils.isEmpty(mStatus)) {
            map.put("STATUS", mStatus);
        }
        apiGetOrderList.setMap(map);
        HttpManager.getInstance().doHttpDeal(apiGetOrderList);
    }

    private void initRv() {
        LinearLayoutManager manager = new LinearLayoutManager(mContext);
        mRv.setLayoutManager(manager);
        List<BeanOrder> orderList = new ArrayList<>();
        mAdpRvMyOrder = new AdpRvMyOrder(R.layout.app_recycle_item_frg_my_order, orderList, this);
        mRv.setAdapter(mAdpRvMyOrder);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        refresh();
    }
}
